<template>
  <el-card style="margin-bottom: 20px;" v-loading="isAjaxing">
    <el-form size="small" label-width="100px" ref="searchRef" :model="searchForm">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="账号" prop="username">
            <el-input class="navSearchInput" v-model="searchForm.username" placeholder="请输入账号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号" prop="phone">
            <el-input class="navSearchInput" v-model="searchForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮箱">
            <el-input class="navSearchInput" v-model="searchForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册时间" prop="register_time">
            <el-date-picker
              value-format="YYYY-MM-DD"
              class="timeSelect"
              v-model="searchForm.register_time"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="登录时间" prop="lastlogin">
            <el-date-picker
              value-format="YYYY-MM-DD"
              class="timeSelect"
              v-model="searchForm.lastlogin"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align: right">
      <el-button size="small" @click="resetFilter">重置</el-button>
      <el-button size="small" @click="search" type="primary">确认</el-button>
    </div>
  </el-card>
  <el-card class="setUsers_box" v-loading="isAjaxing">
    <div>
      <el-button size="mini" @click="getUserFun"><i class="el-icon-refresh-right"></i></el-button>
      <el-button type="primary" size="mini" @click="dialogShow=true;dialogTitle='添加用户'"><i class="el-icon-plus"></i> 新增</el-button>
      <el-button type="danger" size="mini" @click="deleteSelect" :disabled="selectKeys.length == 0"><i class="el-icon-delete"></i> 删除选中</el-button>
      <el-button type="warning" size="mini" :disabled="selectKeys.length == 0"><i class="el-icon-download"></i> 导出选中</el-button>
    </div>
    <el-table :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="ID" prop="id"  min-width="80"></el-table-column>
      <el-table-column label="用户名" prop="username" ></el-table-column>
      <el-table-column label="手机号" prop="phone" min-width="120">
        <template #default="{ row }">
          <span>{{ row.phone ? row.phone : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email">
        <template #default="{ row }">
          <span>{{ row.email ? row.email : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="余额" prop="balance"></el-table-column>
      <el-table-column label="上次登录" prop="lastlogin_time" min-width="150"></el-table-column>
      <el-table-column label="注册时间" prop="register_time" min-width="150"></el-table-column>
      <el-table-column label="操作"  width="150">
        <template #default="{ row }">
          <el-button size="mini" type="primary" @click="editShow(row)">修改</el-button>
          <el-popconfirm
            title="确认要删除该用户账号吗？"
            @confirm="confirmDelete([row.id])"
          >
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="filter.page"
      :page-sizes="[10, 50, 100, 150]"
      :page-size="filter.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
  <el-dialog v-model="dialogShow" :title="dialogTitle" :before-close="beforeClose">
    <el-form :model="dialogForm" :rules="rules" ref="dialogRef">
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="dialogForm.username" placeholder="请输入用户账号"></el-input>
      </el-form-item>
      <el-form-item label="用户密码" :prop="dialogTitle == '添加用户' ? 'password' :''">
        <el-input v-model="dialogForm.password" placeholder="请输入用户密码"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="dialogForm.email" placeholder="请输入用户邮箱"></el-input>
      </el-form-item>
      <el-form-item label="用户手机" prop="phone">
        <el-input v-model="dialogForm.phone" placeholder="请输入用户手机号"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button size="small" type="default" @click="dialogShow = false">取消</el-button>
      <el-button size="small" type="primary" @click="confirmPost" :loading="isSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, reactive, toRefs } from 'vue'
import {  addUser, editUser,getUsers,deleteUser  } from '../../../axios/adminRequest'
import {encryptedData} from '@/utils/encrypted'
import { computedPage } from '../../../utils/utils'
export default {
  name: 'setUsers',
  setup(){
    let { proxy } = getCurrentInstance()
    const state = reactive({
      shortcuts: [
        {
          text: '最近一周',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        }, {
          text: '最近一个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        }, {
          text: '最近三个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        }
      ],
      dialogShow:false,
      isSubmit:false,
      isAjaxing:true,
      searchForm:{
        username:'',
        phone:'',
        email:'',
        lastlogin:[],
        register_time:[]
      },
      filter:{
        page:1,
        limit:10,
      },
      total:0,
      tableData:[],
      dialogTitle:'添加用户',
      dialogForm:{
        username:'',
        password:'',
        phone:'',
        email:''
      },
      rules:{
        username:[{required:true,message:'请输入用户名称',trigger:'blur'}],
        password:[{required:true,message:'请输入用户密码',trigger:'blur'}],
      },
      selectKeys:[]
    })


    const getUserFun = (searchForm) => {
      state.isAjaxing = true
      if(searchForm){
        state.filter = { ...state.filter,...searchForm}
      }
      getUsers(state.filter).then(data=>{
        if(data.code == 0){
          state.total = data.data.total
          state.tableData = data.data.data
        }else{
          proxy.$message.error(data.msg)
        }
        state.isAjaxing = false
      })
    }
    getUserFun()


    const handleSizeChange = (pageSize)=>{
      state.filter.page = 1
      state.filter.limit = pageSize
      getUserFun()
    }

    const handleCurrentChange = (page)=>{
      state.filter.page = page
      getUserFun()
    }

    const confirmDelete = (id) => {
      state.isAjaxing = true
      deleteUser(id).then(res=>{
        if(res.code == 0){
          state.filter.page = computedPage(id.length,state.filter.page,state.filter.limit,state.total)
          proxy.$message.success('删除成功')
          getUserFun()
        }else{
          state.isAjaxing = false
          proxy.$message.error(res.msg)
        }
      })
    }

    const confirmPost = ()=>{
      proxy.$refs.dialogRef.validate(bool=>{
        if(bool){
          let result;
          if(state.dialogTitle=='添加用户'){
            result = addUser({
              key:encryptedData(state.dialogForm)
            })
          }else{
            result = editUser(state.editId,state.dialogForm)
          }
          state.isSubmit = true
          result.then(res=>{
            if(res.code == 0){
              proxy.$message.success('操作成功')
              proxy.$refs.dialogRef.resetFields()
              state.dialogShow = false
              getUserFun()
            }else{
              proxy.$message.error(res.msg)
            }
            state.isSubmit = false
          })
        }
      })
    }

    const editShow = (row)=>{
      state.dialogShow = true;
      state.dialogTitle ='修改用户';
      state.editId = row.id
      state.dialogForm.username = row.username
      state.dialogForm.email = row.email
      state.dialogForm.phone = row.phone
    }

    const beforeClose = (done)=>{
      if(state.isSubmit){
        proxy.$message.warning('暂时无法关闭')
      }else{
        proxy.$refs.dialogRef.resetFields()
        for (const k in state.dialogForm) {
          state.dialogForm[k] = ''
        }
        done()
      }
    }


    const handleSelectionChange = (val)=>{
      let arr = []
      val.forEach(item=>{
        arr.push(item.id)
      })
      state.selectKeys = arr;
    }

    const deleteSelect = () => {
      proxy.$confirm('确认要删除选中的用户吗？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        confirmDelete(state.selectKeys)
      })
    }

    const resetFilter = () => {
      state.filter.page = 1
      proxy.$refs.searchRef.resetFields()
      state.searchForm.register_time_start= ''
      state.searchForm.register_time_end= ''
      state.searchForm.lastlogin_time_start= ''
      state.searchForm.lastlogin_time_end= ''
      getUserFun(state.searchForm)
    }

    const search = ()=>{
      state.filter.page = 1
      state.searchForm.register_time_start=state.searchForm.register_time.length != 0 ? state.searchForm.register_time[0] : ''
      state.searchForm.register_time_end=state.searchForm.register_time.length != 0 ? state.searchForm.register_time[1] : ''
      state.searchForm.lastlogin_time_start=state.searchForm.lastlogin.length != 0 ? state.searchForm.lastlogin[0] : ''
      state.searchForm.lastlogin_time_end=state.searchForm.lastlogin.length != 0 ? state.searchForm.lastlogin[1] : ''
      getUserFun(state.searchForm)
    }

    return {
      ...toRefs(state),
      handleSizeChange,
      handleCurrentChange,
      confirmDelete,
      confirmPost,
      editShow,
      beforeClose,
      handleSelectionChange,
      deleteSelect,
      getUserFun,resetFilter,
      search

    }
  }
}
</script>

<style lang="less" scoped>
.navSearchInput{
  width: 100% !important;
  max-width: 250px !important;
}
&:deep(.timeSelect){
  width: 100% !important;
  max-width: 250px;
}
.setUsers_box{
  .el-table{
    &:deep(.el-table__row){
      .cell{
        font-size: 12px;
      }
    }
  }
}
</style>
